package com.changgou.user.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.common.pojo.BCrypt;
import com.changgou.common.pojo.JwtUtil;
import com.changgou.common.pojo.Result;
import com.changgou.common.pojo.StatusCode;
import com.changgou.core.AbstractCoreController;
import com.changgou.user.pojo.User;
import com.changgou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/****
 * @Author:admin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends AbstractCoreController<User> {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        super(userService, User.class);
        this.userService = userService;
    }
    @GetMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return new Result(false, StatusCode.LOGINERROR,"用户名或者密码不能为空");
        }
        User user = userService.selectByPrimaryKey(username);
        if(user == null){
            return new Result(false, StatusCode.LOGINERROR,"用户名或者密码不正确");
        }
        if(!BCrypt.checkpw(password,user.getPassword())){
            return new Result(false, StatusCode.LOGINERROR,"用户名或者密码不正确");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("role","USER");
        map.put("username",username);
        map.put("success","SUCCESS");
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(map), null);
        Cookie cookie = new Cookie("Authorization",token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(true, StatusCode.OK,"登陆成功",token);


    }


}
